package cn.zjutleo.village_server.service;

import cn.zjutleo.village_server.dto.UserDto;
import cn.zjutleo.village_server.dto.UserUpdateDto;
import cn.zjutleo.village_server.entity.User;
import cn.zjutleo.village_server.exception.apiException.daoException.SelectException;
import cn.zjutleo.village_server.mapper.UserMapper;
import cn.zjutleo.village_server.vo.HostRoughVo;
import cn.zjutleo.village_server.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author : Qin Zhenghan
 * @date : Created in 2021/8/15
 * @description: 用户服务类
 */
@Service
public class UserService {
    @Resource
    private UserMapper userMapper;

    /**
     * 根据用户id查找用户，未找到则抛出异常
     *
     * @param id 用户id
     * @return userVo
     * @throws SelectException 用户查找错误
     */
    public UserVo getExistUserVoById(int id) throws SelectException {
        UserVo userVo = userMapper.selectVoByPrimaryKey(id);
        if (userVo == null) {
            throw new SelectException("用户不存在！");
        }
        return userVo;
    }

    /**
     * 根据用户id查找用户详细信息，未找到则抛出异常
     *
     * @param id 用户id
     * @return user
     * @throws SelectException 用户查找错误
     */
    public User getExistUserDetailById(Integer id) throws SelectException {
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            throw new SelectException("用户不存在！");
        }
        return user;
    }

    /**
     * 根据id获取房东粗略信息VO
     *
     * @param id 房东id
     * @return 房东粗略信息VO
     */
    public HostRoughVo getHostRoughVoById(Integer id) {
        return userMapper.selectHostRoughVoByPrimaryKey(id);
    }

    /**
     * 保存用户
     *
     * @param user 用户实体类
     */
    public void saveUser(User user) {
        userMapper.insertSelective(user);
    }

    /**
     * 根据id删除用户
     *
     * @param id 用户id
     */
    public void deleteUserById(int id) {
        userMapper.deleteByPrimaryKey(id);
    }

    /**
     * 根据id更新用户部分信息
     *
     * @param userUpdateDto 用户DTO
     * @param id 用户id
     */
    public void updateUserById(UserUpdateDto userUpdateDto, int id) {
        User user = new User();
        BeanUtils.copyProperties(userUpdateDto, user);
        user.setId(id);
        userMapper.updateByPrimaryKeySelective(user);
    }
}
